package utils;

import server.BootStrap;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 静态资源输出
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int available =0;
        while(available==0){
            available =inputStream.available();//判断网络是否阻塞，如果为0就是阻塞了
        }
        int resourceSize = available;

        //输出请求头(需要符合http格式)
        outputStream.write(ProtocolHeaderUtil.getHeader200(resourceSize).getBytes());

        //输出内容
        int writtern = 0;
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];//读取的块大小

        while(writtern<resourceSize){
            if(writtern+byteSize>resourceSize){
                //表示读取的超过那个长度。
               byteSize = resourceSize-writtern;
               bytes = new byte[byteSize];
            }

            int read = inputStream.read(bytes);//返回值是什么？

            outputStream.write(bytes);
            outputStream.flush();

            writtern+=read;
        }
    }

    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\","/")+path;
    }
}
